const net = require('net');
const fs = require('fs');
const path = require('path');

const PORT = 3003;
const FILE_PATH = './serverfile/';

const server = net.createServer(socket => {
  console.log('客户端已连接');
  
  // 监听客户端发送的数据
  socket.on('data', data => {
    const str = data.toString();
    
    // 如果是上传文件信息，则准备接收文件
    if (str.startsWith('#')) {
      const info = str.slice(1).split('#');
      const fileName = info[0];
      const fileSize = parseInt(info[1]);
      let recvSize = 0;
      const filePath = FILE_PATH + fileName;
      
      const writeStream = fs.createWriteStream(filePath);
      socket.write('OK');

      socket.on('data', chunk => {
        writeStream.write(chunk);
        recvSize += chunk.length;
        if (recvSize === fileSize) {
          writeStream.end(() => {
            console.log(`文件 ${fileName} 上传完成`);
          });
        }
      });
    }
    
    // 如果是下载请求，则发送文件给客户端
    if (str.startsWith('$')) {
      const fileName = str.slice(1);
      const filePath = FILE_PATH + fileName;
      if (fs.existsSync(filePath)) {
        const fileStats = fs.statSync(filePath);
        const fileSize = fileStats.size;
        const fileInfo = `#${fileName}#${fileSize}`;
        socket.write(fileInfo);
    
        const readStream = fs.createReadStream(filePath);
        readStream.on('data', chunk => {
          socket.write(chunk);
        });
        readStream.on('end', () => {
          console.log(`文件 ${fileName} 发送完成`);
        });
      } else {
        socket.write('NOT_FOUND');
      }
    }

    if (str.startsWith('*')) {
      socket.write('* ');
      fs.readdir(FILE_PATH, (err, files) => {
        if (err) {
          console.error(err);
          socket.write('ERROR');
          return;
        }
        
        // construct the file list string
        const fileList = ['*'];
        for (let i = 0; i < files.length; i++) {
          if (fs.statSync(path.join(FILE_PATH, files[i])).isFile()) {
            fileList.push(files[i] + '*');
          }
        }
        const fileStr = fileList.join('');
        
        // send the file list to the client
        const buf = Buffer.from(fileStr, 'utf-8');
        socket.write(buf);
      });
    }
    
  });

  

  // 监听客户端断开连接
  socket.on('end', () => {
    console.log('客户端已断开连接');
  });

  // 监听连接错误
  socket.on('error', error => {
    console.log('连接出错：', error);
  });
});

server.listen(PORT, () => {
  console.log(`服务已启动，监听端口 ${PORT}`);
});
